<template>
  <div>
    <page-header :title="$t('category.title')">
      <n-button type="primary" @click="handleClickAdd">新增</n-button>
    </page-header>
    <div class="mt-[16px]">
      <n-grid x-gap="12" :cols="4">
        <n-gi>
          <n-select
            clearable
            :options="CATEGORY_STATUS"
            placeholder="请选择状态"
            v-model:value="paginationResult.status"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi>
          <n-input
            placeholder="请输入类别名称"
            v-model:value="paginationResult.name"
            @keyup.enter="handleSearch"
            clearable
          />
        </n-gi>
      </n-grid>
      <div class="mt-[16px]"></div>
      <BasicTable
        :table-props="tableResult"
        :columns="columns"
        :pagination-props="paginationResult"
        :style="{ height: `66vh` }"
      />
    </div>
  </div>
  <category-modal
    v-model:show="showModalResult.show"
    :action-type="showModalResult.actionType"
    :form-data="showModalResult.categoryDetail"
    title="新增产品类别"
    @create-success="handleCreateSuccess"
    @edit-success="handleEditSuccess"
    @close="showModalResult.show = false"
    @cancel="showModalResult.show = false"
  />
</template>
<script setup lang="ts">
import { NButton, NIcon, useDialog, useMessage, NSwitch } from "naive-ui";
import { Trash, CreateOutline } from "@vicons/ionicons5";
import { cloneDeep, get, debounce } from "lodash-es";
import { reactive, ref, onMounted, h } from "vue";
import BasicTable, { useTableHook } from "@/components/normal/basicTable/index";
import CategoryModal from "@/components/biz/categoryModal/index.vue";
import { DictStorage } from "@/storage/dict.storage";
import {
  removeCategory,
  updateStatus,
  getCategories,
} from "@/api/product/category.api";
import { Category } from "@/types/model/product/vos/category.vo";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";

const columns = [
  {
    title: "#",
    type: "index",
    key: "key",
    render: (_: any, index: number) => {
      return `${index + 1}`;
    },
  },
  {
    title: "类别名称",
    key: "name",
  },
  {
    title: "状态",
    key: "status",
    render: (row: Category) => {
      return h(NSwitch, {
        checkedValue: "1",
        uncheckedValue: "2",
        value: row.status,
        onUpdateValue: (val) => {
          row.status = val;
          handleUpdateStatus(row);
        },
      });
    },
  },
  {
    title: "排序",
    key: "sort",
  },
  {
    title: "操作",
    key: "actions",
    align: "right",
    render: (row: any) => {
      return [
        h(
          NButton,
          {
            size: "small",
            secondary: true,
            class: "mr-2",
            onClick: () => handleClickCategoryDetail(row),
          },
          {
            icon: () =>
              h(NIcon, null, {
                default: () => h(CreateOutline),
              }),
          }
        ),
        h(
          NButton,
          {
            size: "small",
            type: "error",
            secondary: true,
            onClick: () => handleClickRemove(row),
          },
          {
            icon: () =>
              h(NIcon, null, {
                default: () => h(Trash),
              }),
          }
        ),
      ];
    },
  },
];

const { tableResult, paginationResult, getDataList } = useTableHook<Category>({
  api: getCategories,
  queryForm: {
    status: undefined,
    name: "",
  },
  likeKeys: ["name"],
});

const message = useMessage();
const dialog = useDialog();

const CATEGORY_STATUS = ref<any[]>([]);

const showModalResult = reactive({
  show: false,
  categoryDetail: {} as Category,
  actionType: ActionTypeEnum.ADD,
});

const handleSearch = debounce(function () {
  paginationResult.page = 1;
  getDataList();
}, 200);

const handleClickAdd = () => {
  showModalResult.actionType = ActionTypeEnum.ADD;
  showModalResult.categoryDetail = {} as Category;
  showModalResult.show = true;
};

const handleCreateSuccess = () => {
  showModalResult.show = false;
  paginationResult.page = 1;
  getDataList();
};

const handleEditSuccess = () => {
  showModalResult.show = false;
  getDataList();
};

const handleClickCategoryDetail = (payload: Category) => {
  console.log(payload);
  showModalResult.categoryDetail = cloneDeep(payload);
  showModalResult.actionType = ActionTypeEnum.EDIT;
  showModalResult.show = true;
};

const handleClickRemove = (payload: Category) => {
  const id = get(payload, "id") || "";
  if (id) {
    dialog.warning({
      title: "警告",
      content: "确定删除吗？",
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
        removeCategory(id).then(() => {
          message.success("删除成功");
          getDataList();
        });
      },
    });
  }
};

const handleUpdateStatus = debounce(async (payload: any) => {
  console.log(payload);
  const id = get(payload, "id") || "";
  const status = get(payload, "status") || "";
  await updateStatus({
    id,
    status,
  });
  message.success("状态更新成功");
  getDataList();
}, 500);

const init = () => {
  CATEGORY_STATUS.value = DictStorage.getDictItemsByCode("pos_category_status");
  getDataList();
};

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
